package com.qw.fmmall.service.impl;

import com.qw.fmmall.dao.UsersMapper;
import com.qw.fmmall.entity.Users;
import com.qw.fmmall.service.UserService;
import com.qw.fmmall.utils.MD5Utils;
import com.qw.fmmall.vo.ResStatus;
import com.qw.fmmall.vo.ResultVO;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UsersMapper usersMapper;

    @Transactional
    public ResultVO userResgit(String name, String pwd) {
        synchronized (this){
//            1.根据用户查询，这个用户是否已经被注册
            Example example = new Example(Users.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("username",name);
            List<Users> users = usersMapper.selectByExample(example);

//            2.如果没有被注册则进行保存操作
            if (users.size() == 0){
                String md5Pwd = MD5Utils.md5(pwd);
                Users user = new Users();
                user.setUsername(name);
                user.setPassword(md5Pwd);
                user.setUserImg("img/default.png");
                user.setUserRegtime(new Date());
                user.setUserModtime(new Date());
                int i = usersMapper.insertUseGeneratedKeys(user);
                if (i>0){
                    return new ResultVO(ResStatus.RES_STATUS1.getValue(),"注册成功",user);
                }else{
                    return new ResultVO(ResStatus.RES_STATUS2.getValue(),"注册失败",null);
                }
            }else{
                return new ResultVO(ResStatus.RES_STATUS2.getValue(),"用户名已经被注册",null);
            }
        }
    }

    @Override
    public ResultVO checkLogin(String name, String pwd) {
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",name);
        List<Users> users = usersMapper.selectByExample(example);

        if (users.size() == 0){
            //用户名不存在
            return new ResultVO(ResStatus.RES_STATUS2.getValue(),"登陆失败，用户名不存在",null);
        }else {
            //对输入的密码进行加密
            //使用加密密码与user中的密码进行匹配
            String mdsPwd = MD5Utils.md5(pwd);
            if (mdsPwd.equals(users.get(0).getPassword())){
                //如果登录验证成功，则需要生成令牌token（token就是按照特定规则生成的字符串）
                //使用jwt规则生成token字符串
                JwtBuilder jwtBuilder = Jwts.builder();

                HashMap<String,Object> map = new HashMap<>();
                map.put("key1","value1");
                map.put("key2","value2");

                String token = jwtBuilder.setSubject(name)
                        .setIssuedAt(new Date())
                        .setId(users.get(0).getUserId() + "")
                        .setClaims(map)
                        .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))
                        .signWith(SignatureAlgorithm.HS256, "qwqwqw")
                        .compact();

                return new ResultVO(ResStatus.RES_STATUS1.getValue(),token,users.get(0));
            }else{
                //密码错误
                return new ResultVO(ResStatus.RES_STATUS2.getValue(),"登陆失败，密码错误",null);
            }
        }
    }
}
